﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenTK;
using OpenTK.Graphics.OpenGL4;

namespace Common {
    public class ModelMesh:GlDisposableObjectBase {
        public Vector3[] Vertices { get; set; }
        public Vector2[] Uvs { get; set; }
        public Vector3[] Normals { get; set; }
        public Vector3[] Tangents { get; set; }
        public Vector3[] BiTangents { get; set; }
        public ushort[] Indices { get; set; }
        public Vbo<Vector3> VertexBuffer { get; set; }
        public Vbo<Vector2> UvBuffer { get; set; }
        public Vbo<Vector3> NormalBuffer { get; set; }
        public Vbo<Vector3> TangentBuffer { get; set; }
        public Vbo<Vector3> BiTangentBuffer { get; set; }
        public Vbo<ushort> IndexBuffer { get; set; }
        public void CreateVbo() {
            if (Vertices != null) {
                VertexBuffer = new Vbo<Vector3>(Vertices);
            }
            if (Uvs != null) {
                UvBuffer = new Vbo<Vector2>(Uvs);
            }
            if (Normals != null) {
                NormalBuffer = new Vbo<Vector3>(Normals);
            }
            if (Tangents != null) {
                TangentBuffer = new Vbo<Vector3>(Tangents);
            }
            if (BiTangents != null) {
                BiTangentBuffer = new Vbo<Vector3>(BiTangents);
            }
            if (Indices != null) {
                IndexBuffer = new Vbo<ushort>(BufferTarget.ElementArrayBuffer, BufferUsageHint.StaticDraw, Indices);
            }
            
        }


        protected override void OnDispose() {
            //protected  void OnDispose() {
            //GlDisposableObjectBase.DisposeObjects(VertexBuffer,UvBuffer,NormalBuffer,TangentBuffer,BiTangentBuffer,IndexBuffer);
            if (VertexBuffer != null) {
                VertexBuffer.Dispose();
            }
            if (UvBuffer != null) {
                UvBuffer.Dispose();
            }
            if (NormalBuffer != null) {
                NormalBuffer.Dispose();
            }
            if (TangentBuffer != null) {
                TangentBuffer.Dispose();
            }
            if (BiTangentBuffer != null) {
                BiTangentBuffer.Dispose();
            }
            if (IndexBuffer != null) {
                IndexBuffer.Dispose();
            }
        }

        //bool disposed = false;

        //public void Dispose() {
        //    GC.SuppressFinalize(this);
        //    if (!disposed) {
        //        OnDispose();
        //    }
        //    disposed = true;
        //}
        //~ModelMesh() {
        //    if (!disposed) {
        //        throw new Exception("model mesh not disposed");
        //    }
        //}
    }
}
